using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MagnoliaTableAdapters;
using System.Data.SqlClient;


public partial class Users : System.Web.UI.Page
{
    static Magnolia.METADATAFIELDDataTable metaTable = new Magnolia.METADATAFIELDDataTable();
    static METADATAFIELDTableAdapter metaAdapter = new METADATAFIELDTableAdapter();
    static Magnolia.SUBMETADATAFIELDDataTable subMetaTable = new Magnolia.SUBMETADATAFIELDDataTable();
    static SUBMETADATAFIELDTableAdapter subMetaAdapter = new SUBMETADATAFIELDTableAdapter();
    static ArrayList tmpDeleteOptionList = new ArrayList();
    static ArrayList perDeleteOptionList = new ArrayList();
    static int indexCounter;
    static int emptyCounter;
    static bool enableButton = false;
    static bool isClientOption = true;

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Meta-Data";

        // hide edit and new buttons for user access
        Btn_Edit.Style.Add("display", "none");
        Btn_New.Style.Add("display", "none");
        Btn_New_SubMeta.Style.Add("display", "none");

        // get user access permissions
        DataTable UserAccessDT = (DataTable)Session["UserAccess"];
        foreach (DataRow dr in UserAccessDT.Rows)
        {
            // edit meta-data
            if (Convert.ToString(dr.ItemArray[0]) == "322")
            {
                Btn_Edit.Style.Add("display", "block");
            }
            // new meta-data
            if (Convert.ToString(dr.ItemArray[0]) == "422")
            {
                Btn_New.Style.Add("display", "block");
                Btn_New_SubMeta.Style.Add("display", "block");
            }

        }

        //Reset the save button to the visiable metadata choice
        if (MetaDataPanel.Style["display"] == "block")
            Btn_Save.OnClientClick = "readStringTagRules(0);";
        else 
            Btn_Save.OnClientClick = "readStringTagRules(1);";
 

        if (!Page.IsPostBack)
        {
            Btn_New_SubMeta.Style.Add("display", "block");
            //hide the submetadata panel and all the hidden Box initially
            SubMetaDataPanel.Style.Add("display", "none");
            listPanel.Style.Add("display", "none");
            Hidden_CheckBox.Style.Add("display", "none");
            Hidden_TextBox.Style.Add("display", "none");
            Hidden_MinusBox.Style.Add("display", "none");

            metaAdapter.Fill(metaTable);
            subMetaAdapter.Fill(subMetaTable);

            //load the metadatalist and submetatlist
            LoadSubList(1);
            LoadList(1);
        }
    }

    //Load the list with given metaData index
    protected void LoadList(int metaIndex)
    {

        ListBox_MetaData.DataTextField = "Name";
        ListBox_MetaData.DataValueField = "ID";
        ListBox_MetaData.DataSource = metaTable;
        ListBox_MetaData.DataBind();

        if (metaTable.Rows.Count > 0)
        {
            Btn_New_SubMeta.Enabled = true;
            if (metaIndex > 0)
            {
                ListBox_MetaData.SelectedValue = metaIndex.ToString();
                LoadList(metaIndex, "Meta-Data: " + ListBox_MetaData.SelectedItem.Text);
            }
            else
            {
                ListBox_MetaData.SelectedIndex = 0;
                LoadList(1, "Meta-Data: " + ListBox_MetaData.SelectedItem.Text);
            }
        }
        else
        {
            Btn_Edit.Enabled = false;
            Btn_New_SubMeta.Enabled = false;
        }
    }
    
    //Overload the function with defined display message
    protected void LoadList(int metaIndex, string message)
    {

        ListBox_MetaData.DataTextField = "Name";
        ListBox_MetaData.DataValueField = "ID";
        ListBox_MetaData.DataSource = metaTable;
        ListBox_MetaData.DataBind();

        ListBox_SubMetaData.SelectedIndex = -1;

        if (metaTable.Rows.Count > 0)
        {
            Btn_Edit.Enabled = true;
            ListBox_MetaData.SelectedValue = metaIndex.ToString();
            Lbl_PageHeader.Text = message;
            LoadForm(Convert.ToInt32(ListBox_MetaData.SelectedValue));
        }
        else
        {
            Btn_Edit.Enabled = false;
            Lbl_PageHeader.Text = "Meta-Data";
            Lbl_EditorAlerts.Visible = false;
        }

        Btn_CancelChanges.Enabled = enableButton;

        if (ListBox_MetaData.SelectedItem.Text == "Client")
            isClientOption = true;
        else
            isClientOption = false;
    }


    //Same for submeta Data list
    protected void LoadSubList(int subMetaIndex)
    {

        ListBox_SubMetaData.DataTextField = "Name";
        ListBox_SubMetaData.DataValueField = "ID";
        ListBox_SubMetaData.DataSource = subMetaTable;
        ListBox_SubMetaData.DataBind();

        if (subMetaTable.Rows.Count > 0)
        {
            if (subMetaIndex > 0)
            {
                ListBox_SubMetaData.SelectedValue = subMetaIndex.ToString();
                LoadSubList(subMetaIndex, "Sub Meta-Data: " + ListBox_SubMetaData.SelectedItem.Text);
            }
            else
            {
                ListBox_SubMetaData.SelectedIndex = 0;
                LoadSubList(1, "Sub Meta-Data: " + ListBox_SubMetaData.SelectedItem.Text);
            }
        }
        else
        {
            Btn_Edit.Enabled = false;
        }
    }

    //Same for submeta Data list
    protected void LoadSubList(int subMetaIndex, string message)
    {

        ListBox_SubMetaData.DataTextField = "Name";
        ListBox_SubMetaData.DataValueField = "ID";
        ListBox_SubMetaData.DataSource = subMetaTable;
        ListBox_SubMetaData.DataBind();

        ListBox_MetaData.SelectedIndex = -1;

        if (subMetaTable.Rows.Count > 0)
        {
            Btn_Edit.Enabled = true;
            ListBox_SubMetaData.SelectedValue = subMetaIndex.ToString();
            Lbl_PageHeader.Text = message;
            LoadSubForm(subMetaIndex);
            Btn_New_SubMeta.Style["display"] = "none";
        }
        else
        {
            Btn_Edit.Enabled = false;
            Lbl_PageHeader.Text = "Sub Meta-Data";
            Lbl_EditorAlerts.Visible = false;
        }

        Btn_CancelChanges.Enabled = enableButton;
    }

    //Reload list when when the selection has change in the metadata
    protected void ListBox_MetaData_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox_MetaData.SelectedValue != "")
        {
            Hidden_MetaDataID.Value = ListBox_MetaData.SelectedValue;
            Hidden_SubMetaID.Value = "-1";
            if (ListBox_MetaData.SelectedItem.Text == "Client")
                isClientOption = true;
            else
                isClientOption = false;
            LoadList(Convert.ToInt32(ListBox_MetaData.SelectedValue));
            Lbl_EditorAlerts.Visible = false;
        }
    }

    //Reload the sub list when the selection has change in the submetadata
    protected void ListBox_SubMetaData_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox_SubMetaData.SelectedValue != "")
        {
            Hidden_SubMetaID.Value = ListBox_SubMetaData.SelectedValue;
            Hidden_MetaDataID.Value = "-1";
            LoadSubList(Convert.ToInt32(ListBox_SubMetaData.SelectedValue));
            Lbl_EditorAlerts.Visible = false;
        }
    }

    //Load the metaForm
    protected void LoadForm(int metaID)
    {
        MetaDataPanel.Style["display"] = "block";
        SubMetaDataPanel.Style["display"] = "none";
        Hidden_MetaDataID.Value = metaID.ToString();
        Hidden_SubMetaID.Value = "-1";
        Magnolia.METADATAFIELDRow metaRow = metaTable.FindByID(metaID);
        TBox_Name.Text = metaRow.Name;
        typeDropDown.Enabled = true;
        typeDropDown.SelectedValue = metaRow.Type;
        HidePanel();
        levelDropDown.SelectedValue = metaRow.Level.ToString();

        string command = "select SubMDFieldID from MetaDatafield where ID=" + metaID;
        string obID = getDataObject(command).ToString();
        if (obID != "")
        {
            FillDropDown(metaRow.SubMDFieldID);
            LoadListOption(metaID, metaRow.SubMDFieldID, false);
            Hidden_ID.Value = metaRow.SubMDFieldID.ToString();
        }
        else
        {
            FillDropDown(0);
            if(metaRow.Type =="list")
                LoadListOption(metaID, 0, false);
        }
    }

    //Load the submetaForm
    private void FillDropDown(int SubIndex)
    {
        DDSubMeta.Items.Clear();
        ListItem subItem = new ListItem("Select", "0");
        DDSubMeta.Items.Add(subItem);

        foreach (Magnolia.SUBMETADATAFIELDRow subMetaRow in subMetaTable.Rows)
        {
            subItem = new ListItem(subMetaRow.Name, subMetaRow.ID.ToString());
            DDSubMeta.Items.Add(subItem);
        }

        DDSubMeta.SelectedIndex = SubIndex;
    }

    //Get the return value with given sql command
    public object getDataObject(string selectSQL)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader = null;
        object ob = new object();

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            reader.Read();
            ob = reader[0];//Only read ONE data in the first of list
            reader.Close();

        }
        catch (Exception err)
        {
            Lbl_EditorAlerts.Visible = true;
            Lbl_EditorAlerts.Text = err.ToString();
        }
        finally
        {
            con.Close();
        }
        return ob;

    }

    //Load the Sub metadata form
    protected void LoadSubForm(int subMetaID)
    {
        Hidden_SubMetaID.Value = subMetaID.ToString();
        Hidden_MetaDataID.Value = "-1";
        MetaDataPanel.Style["display"] = "none";
        SubMetaDataPanel.Style["display"] = "block";
        listPanel.Style["display"] = "none";
        Magnolia.SUBMETADATAFIELDRow subMetaRow = subMetaTable.FindByID(subMetaID);
        SubName.Text = subMetaRow.Name;
        LoadSubOption(subMetaID);
    }

    // Detect if the type of MetaData has been changed
    protected void typeDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        HidePanel();
    }

    //update the listing with the required level
    protected void DropDownLevel_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt32(DropDownLevel.SelectedValue) != 0)
            metaAdapter.FillByLevel(metaTable, Convert.ToInt32(DropDownLevel.SelectedValue));
        else metaAdapter.Fill(metaTable);
        LoadSubList(1);
        LoadList(1);
    }

    //Show the hidden Panel if the list type is selected
    protected void HidePanel()
    {
        if (typeDropDown.SelectedIndex == 6)
        {
            listPanel.Style["display"] = "block";
            LoadListOption(0, 0, false);
        }
        else
            listPanel.Style["display"] = "none";
    }

    //Load the List option with given Subfield ID if the subfield id has been change
    protected void LoadListOption(int metaID, int subFieldID, bool subChange)
    {
        Magnolia.METADATAOPTIONDataTable metaOption = new METADATAOPTIONTableAdapter().GetDataByID(metaID);
        int i = 0;
        int subValue = 0;
        string command;
        string obID;

        Hidden_MetaDataID.Value = metaID.ToString();
        Hidden_SubMetaID.Value = "-1";

        lPanel.Controls.Clear();
        foreach (Magnolia.METADATAOPTIONRow metaOpRow in metaOption)
        {
            bool pass = true;

            if (tmpDeleteOptionList != null)
            {
                foreach (int sIndex in tmpDeleteOptionList)
                {
                    if (i == sIndex)
                    {
                        pass = false;
                        break;
                    }
                }
            }
            if (pass)
            {
                command = "select SubMDValueID from MetaDataOption where ID=" + metaOpRow.ID;
                obID = getDataObject(command).ToString();
                if (obID != "")
                    subValue = metaOpRow.SubMDValueID;

                // new code for color option  !! currently hard-coded based on database only to pass a value to clients
                string optionColor = "";
                if (metaID == 1)
                    optionColor = metaOpRow.Color;
                
                RenderListOption(metaOpRow.ID, metaOpRow.Value, optionColor, i, subValue, subFieldID, subChange);
                i++;
            }
        }
        indexCounter = lPanel.Controls.Count;

        for (int j = 0; j < emptyCounter; j++)
            ListPlusButton(j, subFieldID);

        if (indexCounter == 0 && emptyCounter <= 0)
        {
            ListPlusButton(0, subFieldID);
            emptyCounter++;
        }

        indexCounter = lPanel.Controls.Count;
    }

    //Use to increment the number of empty list option 
    protected void ListPlusButton(int counter, int subFieldID)
    {
        Button BtnPlus = new Button();
        Button BtnMinus = new Button();
        TextBox TBox_ListID = new TextBox();
        TextBox TBox_ListOption = new TextBox();
        Magnolia.SUBMETADATAOPTIONDataTable subOptionTable = new SUBMETADATAOPTIONTableAdapter().GetDataByID(subFieldID);
        DropDownList subValueDrop = new DropDownList();

        BtnPlus.Text = "+";
        BtnMinus.Text = "-";
        BtnPlus.Enabled = enableButton;
        BtnMinus.Enabled = enableButton;
        BtnPlus.Attributes.Add("onclick", "updateHiddenCheckBox();");
        int position = 90 + counter;
        BtnMinus.Attributes.Add("onclick", "updateHiddenTextBox(" + position + ", 0);");

        TBox_ListID.Style.Add("display", "none");
        TBox_ListOption.Enabled = enableButton;

        if (subOptionTable.Count > 0)
        {
            subValueDrop.DataSource = subOptionTable;
            subValueDrop.DataTextField = "Value";
            subValueDrop.DataValueField = "ID";
            subValueDrop.SelectedIndex = 0;
            subValueDrop.DataBind();
        }

        // new code for Client color button (if DDSubMeta.selected is Property)
        HtmlGenericControl colorBox = new HtmlGenericControl("div");
        colorBox.Attributes.Add("class", "colorSelectBox");

        if (enableButton)
        {
            colorBox.Style["background-color"] = "#F2F2F2";
            colorBox.Attributes.Add("enabled", "true");
            colorBox.Attributes.Add("onclick", "showColorSelectorMD(this);");
        }
        else
        {
            colorBox.Style["background-color"] = "#F2F2F2";
            colorBox.Attributes.Add("enabled", "false");
            colorBox.Attributes.Add("onclick", "return false;");
        }

        if (!isClientOption) colorBox.Visible = false;

        //Button BtnColor = new Button();
        //BtnColor.Text = "";
        //BtnColor.Enabled = enableButton;
        ////BtnColor.Style["background-color"] = "#3399FF";
        //BtnColor.Attributes.Add("class", "colorSelectBox");
        //BtnColor.Attributes.Add("onclick", "showColorSelector(this)");

        GenerateTag(BtnPlus, BtnMinus, TBox_ListID, TBox_ListOption, subValueDrop, colorBox);
    }

    //Creation of the list componet to be add in the web page
    protected void RenderListOption(int listID, string listOption, string optionColor, int counter , int subValue, int subFieldID, bool subChange)
    {
        Button BtnPlus = new Button();
        Button BtnMinus = new Button();
        TextBox TBox_ListID = new TextBox();
        TextBox TBox_ListOption = new TextBox();
        Magnolia.SUBMETADATAOPTIONDataTable subOptionTable = new SUBMETADATAOPTIONTableAdapter().GetDataByID(subFieldID);
        DropDownList subValueDrop = new DropDownList();

        BtnPlus.Text = "+";
        BtnMinus.Text = "-";
        BtnPlus.Enabled = enableButton;
        BtnMinus.Enabled = enableButton;
        BtnPlus.Attributes.Add("onclick", "updateHiddenCheckBox();");
        BtnMinus.Attributes.Add("onclick", "updateHiddenTextBox(" + counter + ", " + listID + ");");

        TBox_ListID.Text = listID.ToString();
        TBox_ListID.Style.Add("display", "none");
        TBox_ListOption.Text = listOption;
        TBox_ListOption.Enabled = enableButton;

        if (subOptionTable.Count > 0)
        {
            subValueDrop.DataSource = subOptionTable;
            subValueDrop.DataTextField = "Value";
            subValueDrop.DataValueField = "ID";
            if(!subChange)
                subValueDrop.SelectedValue = subValue.ToString(); ;
            subValueDrop.DataBind();
        }

        // new code for Client color button (if DDSubMeta.selected is Property)
        HtmlGenericControl colorBox = new HtmlGenericControl("div");
        colorBox.Attributes.Add("class", "colorSelectBox");

        //if (optionColor == "")
        //    optionColor = "#F2F2F2";

        if (enableButton)
        {
            colorBox.Style["background-color"] = "#" + optionColor;
            colorBox.Attributes.Add("enabled", "true");
            colorBox.Attributes.Add("onclick", "showColorSelectorMD(this);");
        }
        else
        {
            colorBox.Style["background-color"] = "#" + optionColor;
            colorBox.Attributes.Add("enabled", "false");
            colorBox.Attributes.Add("onclick", "return false;");
        }

        if (!isClientOption) colorBox.Visible = false;

        //Button BtnColor = new Button();
        //BtnColor.Text = "";
        //BtnColor.Enabled = enableButton;
        ////BtnColor.Style["background-color"] = "#3399FF";
        //BtnColor.Attributes.Add("class", "colorSelectBox");
        //BtnColor.Attributes.Add("onclick", "showColorSelector(this)");

        GenerateTag(BtnPlus, BtnMinus, TBox_ListID, TBox_ListOption, subValueDrop, colorBox);
    }

    //add those list componet to in the panel 
    protected void GenerateTag(Button BtnPlus, Button BtnMinus, TextBox TBox_ListID, TextBox TBox_SubOption, DropDownList subValueDrop, HtmlGenericControl colorBox)
    {
        HtmlGenericControl rows = new HtmlGenericControl("div");
        rows.Attributes.Add("class", "row");

        HtmlGenericControl spaceS = new HtmlGenericControl("div");
        spaceS.Attributes.Add("class", "spacerS");

        HtmlGenericControl spaceL = new HtmlGenericControl("div");
        spaceL.Attributes.Add("class", "spacerL");

        HtmlGenericControl spaceL2 = new HtmlGenericControl("div");
        spaceL2.Attributes.Add("class", "spacerL");

        HtmlGenericControl spaceL3 = new HtmlGenericControl("div");
        spaceL3.Attributes.Add("class", "spacerL");

        HtmlGenericControl spaceL4 = new HtmlGenericControl("div");
        spaceL4.Attributes.Add("class", "spacerL");

        rows.Controls.Add(spaceL3);
        rows.Controls.Add(BtnPlus);
        rows.Controls.Add(spaceS);
        rows.Controls.Add(BtnMinus);
        rows.Controls.Add(spaceL);
        rows.Controls.Add(TBox_ListID);
        rows.Controls.Add(TBox_SubOption);
        rows.Controls.Add(spaceL2);
        rows.Controls.Add(subValueDrop);
        rows.Controls.Add(spaceL4);
        rows.Controls.Add(colorBox);
        lPanel.Controls.Add(rows);
    }

    //Same with the metaData 
    protected void LoadSubOption(int subMDFieldID)
    {
        Magnolia.SUBMETADATAOPTIONDataTable subListOp = new SUBMETADATAOPTIONTableAdapter().GetDataByID(subMDFieldID);
        int i = 0;
        Hidden_SubMetaID.Value = subMDFieldID.ToString();
        Hidden_MetaDataID.Value = "-1";

        sLPanel.Controls.Clear();
        foreach (Magnolia.SUBMETADATAOPTIONRow subOp in subListOp)
        {
            bool pass = true;

            if(tmpDeleteOptionList!=null)
            {
                foreach(int sIndex in tmpDeleteOptionList)
                {
                    if(i == sIndex)
                    {
                        pass = false;
                        break;
                    }
                }
            }

            if(pass)
                RenderSubOption(subOp.ID, subOp.Value, i);
            i++;
        }
        indexCounter = sLPanel.Controls.Count;

        for (int j = 0; j < emptyCounter; j++)
            SubPlusButton(j);

        if (indexCounter == 0 && emptyCounter <= 0)
        {
            SubPlusButton(0);
            emptyCounter++;
        }
        indexCounter = sLPanel.Controls.Count;
    }

    //Same with metadata plus button 
    protected void SubPlusButton(int counter)
    {
        Button BtnPlus = new Button();
        Button BtnMinus = new Button();
        TextBox TBox_SubOption = new TextBox();
        TextBox TBox_ListID = new TextBox();

        BtnPlus.Text = "+";
        BtnMinus.Text = "-";
        BtnPlus.Enabled = enableButton;
        BtnMinus.Enabled = enableButton;
        TBox_ListID.Style.Add("display", "none");
        BtnPlus.Attributes.Add("onclick", "updateHiddenCheckBox();");
        int position = 90 + counter;
        BtnMinus.Attributes.Add("onclick", "updateHiddenTextBox(" + position + ", 1);");

        TBox_SubOption.Enabled = enableButton;
        GenerateTag(BtnPlus, BtnMinus, TBox_SubOption, TBox_ListID);
    }

    //Same with metadata render option function 
    protected void RenderSubOption(int listID, string subOption, int counter)
    {
        Button BtnPlus = new Button();
        Button BtnMinus = new Button();
        TextBox TBox_SubOption = new TextBox();
        TextBox TBox_ListID = new TextBox();

        BtnPlus.Text = "+";
        BtnMinus.Text = "-";
        BtnPlus.Enabled = enableButton;
        BtnMinus.Enabled = enableButton;
        BtnPlus.Attributes.Add("onclick", "updateHiddenCheckBox();");
        BtnMinus.Attributes.Add("onclick", "updateHiddenTextBox(" + counter + ", " + listID + ");");

        TBox_ListID.Text = listID.ToString();
        TBox_ListID.Style.Add("display", "none");
        TBox_SubOption.Text = subOption;
        TBox_SubOption.Enabled = enableButton;
        GenerateTag(BtnPlus, BtnMinus, TBox_SubOption, TBox_ListID);
    }

    //Same with metadata generate the componement 
    protected void GenerateTag(Button BtnPlus, Button BtnMinus, TextBox TBox_SubOption, TextBox TBox_ListID)
    {
        HtmlGenericControl rows = new HtmlGenericControl("div");
        rows.Attributes.Add("class", "row");

        HtmlGenericControl spaceS = new HtmlGenericControl("div");
        spaceS.Attributes.Add("class", "spacerS");

        HtmlGenericControl spaceL = new HtmlGenericControl("div");
        spaceL.Attributes.Add("class", "spacerL");

        HtmlGenericControl spaceL3 = new HtmlGenericControl("div");
        spaceL3.Attributes.Add("class", "spacerL");

        rows.Controls.Add(spaceL3);
        rows.Controls.Add(BtnPlus);
        rows.Controls.Add(spaceS);
        rows.Controls.Add(BtnMinus);
        rows.Controls.Add(spaceL);
        rows.Controls.Add(TBox_ListID);
        rows.Controls.Add(TBox_SubOption);
        sLPanel.Controls.Add(rows);
    }
    
    //The event of Edit Button has been clicked
    protected void Btn_Edit_Click(object sender, EventArgs e)
    {
        enableButton = true;
        DisableList();

        FieldEdit();

        ClientClickChoice();
    }

    protected void ClientClickChoice()
    {
        if (SubMetaDataPanel.Style["display"] == "block")
        {
            LoadSubList(Convert.ToInt32(Hidden_SubMetaID.Value));
            Btn_Save.OnClientClick = "readStringTagRules(1);";
        }
        else
        {
            LoadList(Convert.ToInt32(Hidden_MetaDataID.Value));
            Btn_Save.OnClientClick = "readStringTagRules(0);";
        }
    }

    //Disable the List when the editing page or creating is enable
    protected void DisableList()
    {
        ListBox_MetaData.Enabled = false;
        ListBox_MetaData.BackColor = System.Drawing.Color.LightGray;
        ListBox_MetaData.Enabled = false;
        ListBox_SubMetaData.Enabled = false;
        ListBox_SubMetaData.BackColor = System.Drawing.Color.LightGray;
        ListBox_SubMetaData.Enabled = false;

    }

    //Trigger when the cancel or save button is pressed
    protected void EnableList()
    {
        ListBox_MetaData.Enabled = true;
        ListBox_MetaData.BackColor = System.Drawing.Color.White;
        ListBox_MetaData.Enabled = true;
        ListBox_SubMetaData.Enabled = true;
        ListBox_SubMetaData.BackColor = System.Drawing.Color.White;
        ListBox_SubMetaData.Enabled = true;
    }

    //When Edit button is been pressed
    private void FieldEdit()
    {
        TBox_Name.Enabled = enableButton;
        SubName.Enabled = enableButton;
        Btn_Save.Enabled = enableButton;
        Btn_CancelChanges.Enabled = enableButton;
    }

    //Event when the new meta or new submeta is going to be created
    protected void Btn_New_Click(object sender, EventArgs e)
    {

        if (SubMetaDataPanel.Style["display"] == "block")
        {
            listPanel.Style["display"] = "none";
            Hidden_SubMetaID.Value = "0";
            SubName.Text = "";
            DisableList();
            enableButton = true;
            FieldEdit();
            LoadSubOption(0);
        }
        else
        {

            listPanel.Style["display"] = "none";
            Hidden_MetaDataID.Value = "0";
            TBox_Name.Text = "";
            typeDropDown.SelectedIndex = 0;
            levelDropDown.SelectedIndex = 0;
            ListBox_MetaData.SelectedIndex = -1;
            DisableList();
            enableButton = true;
            FieldEdit();
        }
    }

    protected void Btn_CancelChanges_Click(object sender, EventArgs e)
    {
        Resume();
    }

    //Reable the user to choose a meta or submeta data from the list box with pre-selected the index of the one they just edit or created
    protected void Resume()
    {
        Lbl_EditorAlerts.Visible = false;
        emptyCounter = 0;
        enableButton = false;
        Btn_Edit.Enabled = true;
        tmpDeleteOptionList.Clear();
        perDeleteOptionList.Clear();
        EnableList();
        FieldEdit();
        if (Hidden_MetaDataID.Value == "-1")
        {
            int subID = Convert.ToInt32(Hidden_SubMetaID.Value);

            if (subID == 0)
                LoadSubList(1);
            else
                LoadSubList(subID);
        }
        else
        {
            int metaID = Convert.ToInt32(Hidden_MetaDataID.Value);

            if (metaID == 0)
                LoadList(1);
            else
                LoadList(metaID);
        }
    }

   
    protected void Btn_Save_Click(object sender, EventArgs e)
    {
        if (SubMetaDataPanel.Style["display"] == "block")
        {
            SaveSubData();
            //LoadSubList(Convert.ToInt32(Hidden_SubMetaID.Value));
        }
        else
        {
            SaveMetaData();
            //LoadList(Convert.ToInt32(Hidden_MetaDataID.Value));
        }

    }

    //Read from the hiddent text box that was filled by the JavaScrip in the webpage
    //Update or Create the sub metadata accordingly  
    protected void SaveSubData()
    {
        int subMetaID = Convert.ToInt32(Hidden_SubMetaID.Value);

        bool pass = ValidateInput();

        if (!pass)
        {
            LoadSubOption(subMetaID);
            return;
        }

        string saveString;
        saveString = Hidden_TextBox.Text;

        string[] result = saveString.Split('?');

        if (subMetaID != 0)
        {
            Magnolia.SUBMETADATAFIELDRow subMetaRow = subMetaTable.FindByID(subMetaID);
            subMetaRow.Name = SubName.Text;
        }
        else
        {
            Magnolia.SUBMETADATAFIELDRow subMetaRow = subMetaTable.NewSUBMETADATAFIELDRow();
            subMetaRow.Name = SubName.Text;
            subMetaRow.Active = true;
            subMetaTable.Rows.Add(subMetaRow);
            subMetaID = subMetaTable.Rows.Count;
            Hidden_SubMetaID.Value = subMetaID.ToString();
        }

        subMetaAdapter.Update(subMetaTable);

        int j = 0;

        Magnolia.SUBMETADATAOPTIONDataTable subMetaOption = new SUBMETADATAOPTIONTableAdapter().GetData();
        SUBMETADATAOPTIONTableAdapter subMetaOpAdapter = new SUBMETADATAOPTIONTableAdapter();

        //delete the option if there was any option is going to be removed from the database
        foreach (int del in perDeleteOptionList)
        {
            try
            {
                subMetaOpAdapter.Delete(del);
            }
            catch (Exception err)
            {
                alertSQL.Text = "One or more MetaData lists are linked to this SubMeta Option, Please remove those list before Delete this option";
            }
        }

        //Start Update to the datebase 
        for (int i = 0; i < indexCounter; i++)
        {
            //check if the option is empty
            if (result[j++] == "")
            {
                if (result[j] == "")
                    break;
                else
                    result[--j] = "0";
            }
            else
            {
                j--;
            }
            Magnolia.SUBMETADATAOPTIONRow subMetaOptionRow = subMetaOption.FindByID(Convert.ToInt32(result[j++]));

            perDeleteOptionList.Clear();

            if (subMetaOptionRow != null)
            {
                subMetaOptionRow.Value = result[j++];
            }
            else
            {
                subMetaOptionRow = subMetaOption.NewSUBMETADATAOPTIONRow();
                subMetaOptionRow.SubMDFieldID = subMetaID;
                subMetaOptionRow.Value = result[j++];
                subMetaOption.Rows.Add(subMetaOptionRow);
            }
        }
        subMetaOpAdapter.Update(subMetaOption);
        subMetaAdapter.Fill(subMetaTable);
        Resume();
    }

    //Same with Sub meta data option 
    protected void SaveMetaData()
    {
        int metaID = Convert.ToInt32(Hidden_MetaDataID.Value);

        bool pass = ValidateInput();

        if (!pass)
        {
            if(listPanel.Style["display"]=="block")
                LoadListOption(metaID, 0, true);
            return;
        }

        string saveString;

        saveString = Hidden_TextBox.Text;
        string type;

        if (metaID != 0)
        {
            Magnolia.METADATAFIELDRow metaRow = metaTable.FindByID(metaID);
            metaRow.Name = TBox_Name.Text;
            metaRow.Type = typeDropDown.SelectedValue;
            metaRow.Level = Convert.ToInt32(levelDropDown.SelectedValue);
            type = metaRow.Type;
            if (type == "list")
            {
                if (DDSubMeta.SelectedIndex != 0)
                {
                    metaRow.SubMDFieldID = Convert.ToInt32(DDSubMeta.SelectedValue);
                }
            }
        }
        else
        {
            Magnolia.METADATAFIELDRow metaRow = metaTable.NewMETADATAFIELDRow();
            metaRow.Name = TBox_Name.Text;
            metaRow.Type = typeDropDown.SelectedValue;
            metaRow.Level = Convert.ToInt32(levelDropDown.SelectedValue);
            metaRow.Active = true;
            type = metaRow.Type;
            if (type == "list")
            {
                if (DDSubMeta.SelectedIndex > 0)
                {
                    metaRow.SubMDFieldID = Convert.ToInt32(DDSubMeta.SelectedValue);
                }
            }
            metaTable.Rows.Add(metaRow);
            metaID = metaTable.Rows.Count;
            Hidden_MetaDataID.Value = metaID.ToString();
        }
        metaAdapter.Update(metaTable);

        if (type == "list")
        {
            Magnolia.METADATAOPTIONDataTable metaOption = new METADATAOPTIONTableAdapter().GetData();
            METADATAOPTIONTableAdapter metaOpAdapter = new METADATAOPTIONTableAdapter();

            foreach (int del in perDeleteOptionList)
                metaOpAdapter.Delete(del);

            perDeleteOptionList.Clear();

            //Use the special character to separate the string read from the hidden Text box
            string[] result = saveString.Split('?');
            int j = 0;

            for (int i = 0; i < indexCounter; i++)
            {
                if (result[j++] == "")
                {
                    if (result.Length==1 ||result[j] == "")
                        break;
                    else
                        result[--j] = "0";
                }
                else
                {
                    j--;
                }
                Magnolia.METADATAOPTIONRow metaOptionRow = metaOption.FindByID(Convert.ToInt32(result[j++]));
                if (metaOptionRow != null)
                {
                    metaOptionRow.Value = result[j++];
                    int subOp = Convert.ToInt32(result[j++]);
                    if (subOp != -1)
                        metaOptionRow.SubMDValueID = Convert.ToInt32(subOp);
                    metaOptionRow.Color = result[j++];
                }
                else
                {
                    metaOptionRow = metaOption.NewMETADATAOPTIONRow();
                    metaOptionRow.MDFieldID = metaID;
                    metaOptionRow.Value = result[j++];
                    int subOp = Convert.ToInt32(result[j++]);
                    if (subOp != -1)
                        metaOptionRow.SubMDValueID = Convert.ToInt32(subOp);
                    metaOptionRow.Color = result[j++];
                    metaOption.Rows.Add(metaOptionRow);
                }
            }
            metaOpAdapter.Update(metaOption);
        }
        metaAdapter.Fill(metaTable);
        Resume();
    }
   
    //The event is trigger when the Javascrip change it's property
    protected void Hidden_CheckBox_CheckedChanged(object sender, EventArgs e)
    {
        emptyCounter++;

        if (Hidden_MetaDataID.Value == "-1")
        {
            LoadSubOption(Convert.ToInt32(Hidden_SubMetaID.Value));
        }
        else if (Hidden_SubMetaID.Value == "-1")
        {
            LoadListOption(Convert.ToInt32(Hidden_MetaDataID.Value), Convert.ToInt32(Hidden_ID.Value), false);
        }
    }

    //The event is trigger when the Javascrip change it's property
    protected void Hidden_MinusBox_TextChanged(object sender, EventArgs e)
    {
        emptyCounter--;
        string deleteString = Hidden_MinusBox.Text;
        string[] deleteList = deleteString.Split('?');

        tmpDeleteOptionList.Add(Convert.ToInt32(deleteList[0]));
        perDeleteOptionList.Add(Convert.ToInt32(deleteList[1]));

        Hidden_MinusBox.Text = "";

        if (MetaDataPanel.Style["display"] == "block")
        {
            int tmpType = typeDropDown.SelectedIndex;
            int tmpLeve = levelDropDown.SelectedIndex;
            string tmpName = TBox_Name.Text;
            LoadListOption(Convert.ToInt32(Hidden_MetaDataID.Value), Convert.ToInt32(Hidden_ID.Value), false);

            typeDropDown.SelectedIndex = tmpType;
            levelDropDown.SelectedIndex = tmpLeve;
            if (typeDropDown.SelectedIndex == 6 && Hidden_ID.Value == "")
            {
                listPanel.Style["display"] = "block";
                LoadListOption(0, 0, false);
            }
            TBox_Name.Text = tmpName;
            ListBox_MetaData.SelectedIndex = -1;
        }
        else if (SubMetaDataPanel.Style["display"] == "block")
        {
            LoadSubOption(Convert.ToInt32(Hidden_SubMetaID.Value));
        }
    }

    //The event is trigger the option of the meta data been modified
    protected void DDSubMeta_SelectedIndexChanged(object sender, EventArgs e)
    {
        Hidden_ID.Value = DDSubMeta.SelectedValue;
        LoadListOption(Convert.ToInt32(Hidden_MetaDataID.Value), Convert.ToInt32(DDSubMeta.SelectedValue), true);
    }

    //Check if the input are valided
    public bool ValidateInput()
    {
        ArrayList errorList = new ArrayList();
        if (MetaDataPanel.Style["display"] == "block")
        {
            if (TBox_Name.Text.Trim() == "")
                errorList.Add("* Meta-Data Name Field Can Not be Blank");
        }
        else if (SubMetaDataPanel.Style["display"] == "block")
        {
            if (SubName.Text.Trim() == "")
                errorList.Add("* SubMeta-Data Name Field Can Not be Blank");
        }

        if (errorList.Count != 0)
        {
            Lbl_EditorAlerts.Text = "";
            foreach (string msg in errorList)
                Lbl_EditorAlerts.Text += msg + "<BR>";

            Lbl_EditorAlerts.Visible = true;
            return false;
        }
        return true;
    }

    protected void Btn_New_SubMeta_Click(object sender, EventArgs e)
    {
        Btn_Save.OnClientClick = "readStringTagRules(1);";

        Hidden_SubMetaID.Value = Convert.ToString(0);
        Hidden_MetaDataID.Value = "-1";
        MetaDataPanel.Style["display"] = "none";
        SubMetaDataPanel.Style["display"] = "block";
        listPanel.Style["display"] = "none";

        Lbl_EditorAlerts.Visible = false;

        listPanel.Style["display"] = "none";
        Hidden_SubMetaID.Value = "0";
        SubName.Text = "";
        DisableList();
        enableButton = true;
        FieldEdit();
        LoadSubOption(0);
    }
}
